import React, { Component } from "react";
import { Icon, message, Spin, Pagination, Popconfirm } from "antd";
import { connect } from "dva";
import TopSelect from "./components/TopSelect";
import Card from "./components/Card";
import { getChannelText } from "../../channelType";
import styles from "./index.less";
// import background from './background.png';
// import ZWWX from '../../../assets/channel-types/zwwx.png';
// import ZWDD from '../../../assets/channel-types/zwdd.png';
// import APP from '../../../assets/channel-types/app.png';
import YJ from "../../../assets/channel-types/yj.png";
import DX from "../../../assets/channel-types/dx.png";
import DINGTALK from "../../../assets/channel-types/dingdingtalk.png";
import DINGROBOT from "../../../assets/channel-types/dingdingrobot.png";
import DINGQUN from "../../../assets/channel-types/dingdingqun.png";
import SYSTEM from "../../../assets/channel-types/system.png";
import LANXIN from "../../../assets/channel-types/lanxin.png";
import { getCurrentTenant } from "../../../utils/utils";

@connect(stores => ({
  channelData: stores.channelModel,
  channelDictionaryModel: stores.channelDictionaryModel
}))
class ChannelManager extends Component {
  state = {
    pageSize: 5,
    pageNum: 1,
    total: 0,
    channelName: "", // 渠道名称
    channelType: "", // 渠道类型  1 政务微信 2 app 3 网页客户端 4 短信 5 邮件
    channelList: [],
    loading: false,
    orderTime: "desc",
    useStatus: null // 启用状态 0-已停用、1-已启用
  };

  channelIcons = {
    4: DX,
    10: YJ,
    12: DINGQUN,
    7: DINGTALK,
    11: DINGROBOT,
    6: SYSTEM,
    2: LANXIN,
    3: LANXIN
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.getList();
    dispatch({
      type: "channelDictionaryModel/channelsTypes",
      payload: {}
    });
  }

  getList = () => {
    const { dispatch } = this.props;
    const {
      pageSize,
      pageNum,
      channelName,
      channelType,
      orderTime,
      useStatus
    } = this.state;
    const payload = {
      pageSize,
      pageNum,
      channelName,
      channelType,
      orderTime,
      useStatus
    };
    this.setState({ loading: true });
    dispatch({ type: "channelModel/channelList", payload }).then((res = {}) => {
      if (res.success) {
        this.setState({
          channelList: res.datas,
          total: res.totalCount
        });
      } else {
        message.warning(`查询失败${res.errMsg}`);
      }
      this.setState({ loading: false });
    });
  };

  edit = id => {
    const { history } = this.props;
    history.push(
      `/messageCenter/channelManager/channelList/channelRegister?pushChannelId=${id}`
    );
  };

  desc = id => {
    const { history } = this.props;
    history.push(
      `/messageCenter/channelManager/channelList/channelDetail?pushChannelId=${id}`
    );
  };

  test = code => {
    const { dispatch } = this.props;
    dispatch({
      type: "channelRegisterModel/test",
      payload: {
        channelCode: code,
        tenantCode: getCurrentTenant().tenantCode[0]
      }
    }).then(res => {
      if (res.success) {
        message.success("测试成功！");
      } else {
        message.error("测试失败！");
      }
    });
  };

  del = pushChannelId => {
    const { dispatch } = this.props;
    const payload = { pushChannelId };
    this.setState({
      loading: true
    });
    dispatch({ type: "channelModel/delChannel", payload }).then((res = {}) => {
      if (res.success) {
        message.success("删除成功");
        const { channelList } = this.state;

        if (channelList.length === 1) {
          const { pageNum } = this.state;
          this.setState(
            {
              pageNum: pageNum - 1
            },
            () => {
              this.getList();
            }
          );
        } else {
          this.getList();
        }
      } else {
        this.setState({
          loading: false
        });
        message.error(`删除失败:${res.errMsg}`);
      }
    });
  };

  top = (pushChannelId, isTop) => {
    const { dispatch } = this.props;
    const payload = { pushChannelId, topStatus: isTop ? 0 : 1 };
    this.setState({
      loading: true
    });
    dispatch({ type: "channelModel/channelTop", payload }).then((res = {}) => {
      if (res.success) {
        message.success(isTop ? "取消置顶成功" : "置顶成功");
        this.getList();
      } else {
        message.error(
          isTop ? `取消置顶失败:${res.errMsg}` : `置顶失败:${res.errMsg}`
        );
      }
      this.setState({
        loading: false
      });
    });
  };

  chooseChannelType = type => {
    this.setState(
      {
        channelType: type,
        pageNum: 1
      },
      () => {
        this.getList();
      }
    );
  };

  chooseUseStatus = useStatus => {
    this.setState(
      {
        useStatus,
        pageNum: 1
      },
      () => {
        this.getList();
      }
    );
  };

  changeChannelName = channelName => {
    this.setState(
      {
        channelName,
        pageNum: 1
      },
      () => {
        this.getList();
      }
    );
  };

  paginationOnChange = page => {
    this.setState(
      {
        pageNum: page
      },
      () => {
        this.getList();
      }
    );
  };

  onSearch = () => {
    this.setState(
      {
        pageNum: 1
      },
      () => {
        this.getList();
      }
    );
  };

  // 注册
  handleAdd = () => {
    const { history } = this.props;
    history.push("/messageCenter/channelManager/channelList/channelRegister");
  };

  // 注册
  updateStatus = ({ pushChannelId, useStatus }) => {
    const { dispatch } = this.props;
    this.setState({ loading: true });
    dispatch({
      type: "channelDictionaryModel/updateStatus",
      payload: { pushChannelId, useStatus: useStatus === 1 ? 0 : 1 },
      callback: () => {
        this.setState({ loading: false });
        this.getList();
      }
    });
  };

  render() {
    const { loading, channelList, pageSize, total, pageNum } = this.state;
    const { channelDictionaryModel } = this.props;
    const { channelsTypesData = [] } = channelDictionaryModel;

    const restArr = [];
    for (let index = 0; index < 5 - channelList.length; index += 1) {
      restArr.push(index);
    }

    return (
      <div className={styles.root}>
        <Spin spinning={loading}>
          <TopSelect
            chooseChannelType={this.chooseChannelType}
            changeChannelName={this.changeChannelName}
            chooseUseStatus={this.chooseUseStatus}
            channelTypeList={[
              { value: undefined, des: "全部" },
              ...channelsTypesData
            ]}
          />
          <div className={styles.body}>
            <div
              className={styles.add}
              style={{
                color: getCurrentTenant().id === "100000" ? "#ccc" : "#888"
              }}
              onClick={
                getCurrentTenant().id === "100000" ? null : this.handleAdd
              }
            >
              <Icon type="plus" />
              新建渠道
            </div>

            {channelList.map((item, i) => (
              <Card
                key={i}
                img={
                  item.channelType ? this.channelIcons[item.channelType] : null
                }
                title={item.description}
                desc={`${
                  item.channelCode
                }\xa0\xa0\xa0\xa0\xa0\xa0\xa0\xa0${getChannelText(
                  channelsTypesData,
                  item.channelType
                )}`}
                id={item.pushChannelId}
                topStatus={item.topStatus}
                tenantName={item.tenantName}
                topClick={id => this.top(id, item.topStatus === 1)}
                foot={[
                  {
                    name: item.useStatus === 1 ? "停用" : "启用",
                    onClick: () => {
                      this.updateStatus(item);
                    }
                  },
                  {
                    name:
                      item.useStatus === 1 ? ( // 0：只可查看，1：可以编辑和删除
                        <span style={{ color: "#ccc" }}>编辑</span>
                      ) : (
                        "编辑"
                      ),
                    onClick: item.useStatus !== 1 && this.edit
                  },
                  {
                    name:
                      item.useStatus === 1 ? (
                        <span style={{ color: "#ccc" }}>删除</span>
                      ) : (
                        <Popconfirm
                          placement="top"
                          icon={<Icon type="question-circle" theme="filled" />}
                          title={`是否删除【${item.description}】推送渠道`}
                          onConfirm={() => this.del(item.pushChannelId)}
                          okText="确认"
                          cancelText="取消"
                        >
                          删除
                        </Popconfirm>
                      ),
                    onClick: false
                  },
                  { name: "详情", onClick: this.desc },
                  {
                    name: (
                      <Popconfirm
                        placement="top"
                        icon={<Icon type="question-circle" theme="filled" />}
                        title={`是否测试【${item.description}】推送渠道`}
                        onConfirm={() => this.test(item.channelCode)}
                        okText="确认"
                        cancelText="取消"
                      >
                        测试
                      </Popconfirm>
                    ),
                    onClick: false
                  }
                ]}
              />
            ))}
            {restArr.map(n => (
              <div key={n} />
            ))}
          </div>
          <div>
            <Pagination
              className={styles.pagination}
              total={total}
              showTotal={totalCount => `共有 ${totalCount} 条`}
              defaultCurrent={1}
              pageSize={pageSize}
              current={pageNum}
              showQuickJumper
              onChange={this.paginationOnChange}
            />
          </div>
        </Spin>
      </div>
    );
  }
}

export default ChannelManager;
